package com.gxa.hotel.portal.service.impl;

import com.gxa.hotel.core.util.RestUtils;
import com.gxa.hotel.portal.service.GoodsCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class GoodsCacheServiceImpl implements GoodsCacheService {
    //准备redis操作对象
    @Autowired
    private RedisTemplate<String,Object> redisTemplate=null;
    public static final String GOODS_CACHE="Goods:";

    @Override
    public Object selectGoodsCache(Long id) throws Exception {
        ValueOperations<String, Object> stringPos = redisTemplate.opsForValue();
        Object data=null;
         data =  stringPos.get(GOODS_CACHE + id);

        if (StringUtils.isEmpty(data)){
            log.info("通过数据库方式读取数据");
            String url="http://localhost:8080/goods/selectById";
            MultiValueMap<String,Object> parmas =new LinkedMultiValueMap<>();
            parmas.add("id", id);
             Map  map = RestUtils.postWithParams(url, null, parmas);

//            Goods data = JsonUtil.read(map.get("data").toString(), Goods.class);
            stringPos.set(GOODS_CACHE + id,map.get("data"),2, TimeUnit.HOURS);
            data=map.get("data");
        }
        log.info("通过缓存读取数据");
//        Goods read = JsonUtil.read(value, Goods.class);
        return data;
    }
    @Override
    public Boolean deleteGacheById(Long id) {
        String key= GOODS_CACHE+id;
        Boolean delete = redisTemplate.delete(key);

        return delete;
    }
}
